import * as CtiClient from './ctiClient.js';

let mqDestination;
let mqClient;  //mq连接client
let subscribeId; //mq订阅id
export function connect(mqService,destination){ 
      mqDestination = destination;
      if (!mqClient || !mqClient.connected) {
            mqClient = Stomp.client(mqService);
      }
      // mqClient.connect(Config.getHeader(),onConnect,onFailed);
      const headers = {
            login: 'admin',
            passcode: 'YunEasy_eos'
      };
        // SockJS does not support heart-beat: disable heart-beats
        mqClient.heartbeat.outgoing = 180000;
        mqClient.heartbeat.incoming = 180000;
  
        mqClient.connect(headers, onConnected, onFailed);
}
export function disconnect(){
     //关闭连接
     if (subscribeId) {
      mqClient.unsubscribe(subscribeId);
      mqClient.disconnect();
      subscribeId = "";
    } 
}

function onConnected(frame){
      console.log("mq订阅: " + frame);
      if (!mqClient.connected) {
            connect();
            return false;
      }
      let object = mqClient.subscribe(mqDestination, responseCallback,{'auto-delete':true,'x-message-ttl':30000});
      subscribeId = object.id;
  
}
// 发送消息
export function sendMsg(message){
      
      if (mqClient && mqClient.connected) {
            mqClient.send("/queue/mpccReceiver",{"content-type":"text/plain","x-message-ttl":"30000"},message);
      }else{
            console.warn("mqClient异常");
      }
}

 // 失败回调
function onFailed(frame){
      console.log("连接失败"+frame);
}

// 响应回调
function responseCallback(frame){
      var jsonStr=JSON.parse(frame.body);
      if (typeof jsonStr == "string" || jsonStr instanceof String) {
            jsonStr = JSON.parse(jsonStr);
      }
      CtiClient.onEvent(jsonStr.type,jsonStr.status,jsonStr.method,jsonStr.retCode,jsonStr);
} 
 